let fs = require('fs');
const sugar = loader('sugar')
global.monitor={};
//监控所有的监控器
module.exports=function(){
  if(!gem_config.features.hotDeployment)return;
  fs.readdirSync(__dirname).forEach(filename=>{
    //把各个子热监控启动起来
    if(filename.endsWith(".js") && filename!=="Monitor.js") loader(__dirname+"\\"+filename)();
    fs.watchFile(__dirname+"\\"+filename,{interval:100},()=>{
      global.clear();
      console.log('\033[30;43m CONDUCT \033[40;33m Compilation... '+filename)
      console.time('\033[42;30m DONE \033[40;32m Compiled successfully in ');
      //先停止该文件所监听的文件,然后清除该模块的缓存重启模块
      loader(global.monitor[sugar.path(__dirname+"\\"+filename)].stop(),true)();
      global.clear();
      console.timeEnd('\033[42;30m DONE \033[40;32m Compiled successfully in ');
      console.log();
    });
  })
  global.monitor[__filename]={stop}
}

function stop(){
  delete global.monitor[__filename];
  //关闭热部署先的所有模块监控
  fs.readdirSync(__dirname).forEach(filename=>{
    //停止这个文件的监控
    fs.unwatchFile(__dirname+"\\"+filename);
    //关闭该模块所监控的文件
    global.monitor[__dirname+"\\"+filename] &&
    global.monitor[__dirname+"\\"+filename].stop()
  })

  //清理当前文件缓存
  delete require.cache[__filename];
  Object.keys(global.monitor).forEach(e=>{global.monitor[e].stop();})
  return __filename;
}
